﻿using Max.Ph5_2009A.NewShopping.DTO;
using Max.Ph5_2009A.NewShopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.Ph5_2009A.NewShopping.API.Controllers
{
    /// <summary>
    /// 基类的控制器（只有CRUD）
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class BaseController<T> : ControllerBase where T : class, new()
    {
        IBaseService<T> _service;

        public BaseController(IBaseService<T> service)
        {
            _service = service;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual IActionResult Insert(T t)
        {
            ResponseResultOutputDto dto = new();

            //判断参数是否有效
            if (!ModelState.IsValid)
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = "参数有误";
                return BadRequest(dto);
            }

            //调用业务
            int result = _service.Insert(t);

            if (result < 0)
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = Domain.Shared.ResponseResultStateCode.系统错误.ToString();
            }

            //返回值
            return Ok(dto);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        [HttpDelete]
        public virtual IActionResult Delete(List<T> ts)
        {
            ResponseResultOutputDto dto = new();

            dto.Data = _service.Delete(ts);

            return Ok(dto);
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPut]
        public virtual IActionResult Update(T t)
        {
            ResponseResultOutputDto dto = new();

            dto.Data = _service.Update(t);

            return Ok(dto);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual IActionResult Select()
        {
            ResponseResultOutputDto dto = new();

            dto.Data = _service.Select();

            return Ok(dto);
        }
    }
}
